package com.orange.common.web.interceptor;

import com.orange.common.web.trace.TraceIdConstant;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Description: 已使用到自动装配
 */
@Component
public class TraceIDInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //配置mdc
        String traceId = request.getHeader("traceId");
        if(traceId==null||traceId==""){
            //从新建立
            traceId = UUID.randomUUID().toString().replace("-", "");
            MDC.put(TraceIdConstant.TRACE_ID,traceId);
            return true;
        }
        MDC.put(TraceIdConstant.TRACE_ID,traceId);
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(TraceIdConstant.TRACE_ID);
    }
}
